package com.xiaoxiang.text.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxiang.text.dao.DynamicDao;
import com.xiaoxiang.text.entity.Dynamic;
import com.xiaoxiang.text.service.DynamicService;
import com.xiaoxiang.text.util.BloomFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Dynamic)表服务实现类
 *
 * @author haha
 * @since 2022-03-22 13:16:47
 */
@Service("dynamicService")
public class DynamicServiceImpl extends ServiceImpl<DynamicDao, Dynamic> implements DynamicService {

    @Resource
    private BloomFilter bloomFilter;

    @Value("${dynamic.likePrefix}")
    private String likePrefix;

    @Value("${dynamic.browsePrefix}")
    private String browsePrefix;


    @Override
    public List<Dynamic> getRecommendList(Integer size) {
        Page<Dynamic> page = new Page<>();
        page.addOrder(OrderItem.desc("id"));
        page.setMaxLimit(size.longValue());
        return this.page(page).getRecords();
    }

    @Override
    public List<Dynamic> pageList(Page<Dynamic> page, QueryWrapper<Dynamic> dynamicQueryWrapper) {
        page.addOrder(OrderItem.desc("id"));
        return this.page(page, dynamicQueryWrapper).getRecords();
    }

    @Override
    public boolean like(Long dynamicId, Long userId) {
        if (bloomFilter.contains(likePrefix + userId, dynamicId.toString())) {
            return false;
        }
        bloomFilter.add(likePrefix + userId, dynamicId.toString());
        this.baseMapper.like(dynamicId);
        return true;
    }

    @Override
    public boolean cancelLike(Long dynamicId, Long userId) {
        if (!bloomFilter.contains(likePrefix + userId, dynamicId.toString())) {
            return false;
        }
        bloomFilter.remove(likePrefix + userId, dynamicId.toString());
        this.baseMapper.cancelLike(dynamicId);
        return true;
    }

    @Override
    public boolean browse(Long dynamicId, Long userId) {
        if (bloomFilter.contains(browsePrefix + userId, dynamicId.toString())) {
            return false;
        }
        bloomFilter.add(browsePrefix + userId, dynamicId.toString());
        this.baseMapper.browse(dynamicId);
        return true;
    }

    @Override
    public boolean comment(Long dynamicId, Long userId) {
        this.baseMapper.comment(dynamicId);
        return true;
    }
}
